/*
 * HSM Proxy Project.
 * Copyright (C) 2013 FedICT.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License version
 * 3.0 as published by the Free Software Foundation.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, see 
 * http://www.gnu.org/licenses/.
 */

package be.fedict.hsm.entity;

import java.io.Serializable;
import java.util.List;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Query;
import javax.persistence.Table;

@Entity
@Table(name = Constants.TABLE_NAME_PREFIX + "credential")
@NamedQueries({ @NamedQuery(name = CredentialEntity.QUERY_APP, query = "SELECT c FROM CredentialEntity AS c "
		+ "WHERE c.application = :application") })
public class CredentialEntity implements Serializable {

	private static final long serialVersionUID = 1L;

	public static final String QUERY_APP = "ce.app";

	@Id
	private String hash;

	@Column(length = 4 * 1024)
	private byte[] credential;

	@ManyToOne
	private ApplicationEntity application;

	public CredentialEntity() {
		super();
	}

	public CredentialEntity(String hash, byte[] credential,
			ApplicationEntity application) {
		this.hash = hash;
		this.credential = credential;
		this.application = application;
	}

	public ApplicationEntity getApplication() {
		return this.application;
	}

	public static List<CredentialEntity> getCredentials(
			EntityManager entityManager, ApplicationEntity applicationEntity) {
		Query query = entityManager.createNamedQuery(QUERY_APP);
		query.setParameter("application", applicationEntity);
		return query.getResultList();
	}

	public String getHash() {
		return this.hash;
	}

	public void setHash(String hash) {
		this.hash = hash;
	}

	public byte[] getCredential() {
		return this.credential;
	}
}
